from lib.poller import Poller
from django import db
import time
import sys
import yapdi
import os
import config


class PollerDaemon:
    """
    Daemon to run polling operations on a set interval
    """
    poller = Poller()
    poller.servers = config.PCONFIG['servers']
    

    def run(self):
        self.poller.get_xml()
        self.poller.parsexml()
        self.poller.stashit()


daemon = yapdi.Daemon(pidfile='/var/run/pd.pid')
pollerd = PollerDaemon()

if len(sys.argv) < 2:
    print "Usage: daemon.py start | stop"
    sys.exit(1)

command = sys.argv[1]
if command == "start":
    retcode = daemon.daemonize()
    if retcode == yapdi.OPERATION_SUCCESSFUL:
        pollerd.poller.logger.info("Daemon started: %s." % daemon.pidfile)
    else:
        pollerd.poller.logger.error("Daemon failure: %s" % retcode)    
elif command == "stop":
    print "Stopping mm xml daemon..."
    pid = open('/var/run/pd.pid', 'r').readline()
    os.system("kill -9 %s" % pid)
    print "xml daemon killed."
    os.system("rm /var/run/pd.pid")
    sys.exit()
else:
    print "Usage: daemon.py start | stop"
    sys.exit()

while 1:
    pollerd.run()
    db.reset_queries()
    time.sleep(5)

        
